<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>图像转ICO工具 - 精美图标转换器</title>
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"
    />
    <script src="https://cdn.jsdelivr.net/npm/image-conversion/build/conversion.min.js"></script>
    <style>
      :root {
        --primary-color: #4361ee;
        --secondary-color: #3f37c9;
        --accent-color: #4895ef;
        --light-color: #f8f9fa;
        --dark-color: #212529;
        --success-color: #4cc9f0;
        --warning-color: #f72585;
      }

      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      }

      body {
        background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        min-height: 100vh;
        color: var(--dark-color);
        line-height: 1.6;
      }

      .container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 2rem;
      }

      header {
        text-align: center;
        margin-bottom: 3rem;
        padding: 1rem;
        background-color: rgba(255, 255, 255, 0.8);
        border-radius: 15px;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
      }

      h1 {
        font-size: 2.5rem;
        margin-bottom: 0.5rem;
        color: var(--primary-color);
        background: linear-gradient(
          to right,
          var(--primary-color),
          var(--warning-color)
        );
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }

      .subtitle {
        font-size: 1.1rem;
        color: #666;
        margin-bottom: 1rem;
      }

      .converter-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        background-color: white;
        border-radius: 15px;
        padding: 2rem;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;
      }

      .converter-container:hover {
        box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
      }

      .upload-area {
        width: 100%;
        max-width: 600px;
        border: 2px dashed var(--accent-color);
        border-radius: 10px;
        padding: 3rem 2rem;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s ease;
        margin-bottom: 2rem;
        position: relative;
        background-color: rgba(72, 149, 239, 0.05);
      }

      .upload-area:hover {
        background-color: rgba(72, 149, 239, 0.1);
        border-color: var(--primary-color);
      }

      .upload-area i {
        font-size: 3rem;
        color: var(--accent-color);
        margin-bottom: 1rem;
      }

      .upload-area h3 {
        margin-bottom: 0.5rem;
        color: var(--primary-color);
      }

      .upload-area p {
        color: #666;
      }

      #fileInput {
        display: none;
      }

      .options {
        width: 100%;
        max-width: 600px;
        margin-bottom: 2rem;
      }

      .option-group {
        margin-bottom: 1.5rem;
      }

      .option-group h4 {
        margin-bottom: 0.8rem;
        color: var(--primary-color);
      }

      .size-options {
        display: flex;
        flex-wrap: wrap;
        gap: 0.8rem;
      }

      .size-option {
        display: flex;
        align-items: center;
      }

      .size-option input[type='checkbox'] {
        margin-right: 0.5rem;
      }

      .custom-size {
        display: flex;
        align-items: center;
        margin-top: 1rem;
      }

      .custom-size input {
        width: 60px;
        padding: 0.5rem;
        margin: 0 0.5rem;
        border: 1px solid #ddd;
        border-radius: 5px;
        text-align: center;
      }

      .btn {
        padding: 0.8rem 1.5rem;
        border: none;
        border-radius: 50px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        display: inline-flex;
        align-items: center;
        justify-content: center;
      }

      .btn-primary {
        background-color: var(--primary-color);
        color: white;
      }

      .btn-primary:hover {
        background-color: var(--secondary-color);
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(67, 97, 238, 0.4);
      }

      .btn-secondary {
        background-color: white;
        color: var(--primary-color);
        border: 2px solid var(--primary-color);
      }

      .btn-secondary:hover {
        background-color: rgba(67, 97, 238, 0.1);
      }

      .btn i {
        margin-right: 0.5rem;
      }

      .preview-container {
        width: 100%;
        max-width: 600px;
        margin-top: 2rem;
        display: none;
      }

      .preview-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1rem;
      }

      .preview-images {
        display: flex;
        flex-wrap: wrap;
        gap: 1rem;
      }

      .preview-item {
        text-align: center;
        background-color: #f8f9fa;
        padding: 1rem;
        border-radius: 10px;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
      }

      .preview-item img {
        max-width: 100px;
        height: auto;
        margin-bottom: 0.5rem;
      }

      .download-btn {
        margin-top: 2rem;
        display: none;
      }

      footer {
        text-align: center;
        margin-top: 3rem;
        padding: 1rem;
        color: #666;
        font-size: 0.9rem;
      }

      .features {
        display: flex;
        justify-content: space-around;
        flex-wrap: wrap;
        margin: 3rem 0;
        gap: 1.5rem;
      }

      .feature {
        flex: 1;
        min-width: 250px;
        background-color: white;
        padding: 1.5rem;
        border-radius: 10px;
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
        text-align: center;
        transition: all 0.3s ease;
      }

      .feature:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
      }

      .feature i {
        font-size: 2rem;
        color: var(--accent-color);
        margin-bottom: 1rem;
      }

      .feature h3 {
        margin-bottom: 0.5rem;
        color: var(--primary-color);
      }

      @media (max-width: 768px) {
        h1 {
          font-size: 2rem;
        }

        .converter-container {
          padding: 1.5rem;
        }

        .upload-area {
          padding: 2rem 1rem;
        }
      }
    </style>
  </head>
  <body>
    <div class="container">
      <header>
        <h1>图像转ICO工具</h1>
        <p class="subtitle">将PNG、JPG等图像转换为网站图标(ICO)格式</p>
      </header>

      <div class="converter-container">
        <div class="upload-area" id="uploadArea">
          <i class="fas fa-cloud-upload-alt"></i>
          <h3>拖放图像文件到此处</h3>
          <p>或点击选择文件 (支持PNG, JPG, JPEG, GIF, SVG)</p>
          <input type="file" id="fileInput" accept="image/*" />
        </div>

        <div class="options">
          <div class="option-group">
            <h4>选择图标尺寸 (像素)</h4>
            <div class="size-options">
              <label class="size-option">
                <input type="checkbox" name="size" value="16" checked />
                16×16
              </label>
              <label class="size-option">
                <input type="checkbox" name="size" value="32" checked />
                32×32
              </label>
              <label class="size-option">
                <input type="checkbox" name="size" value="48" checked />
                48×48
              </label>
              <label class="size-option">
                <input type="checkbox" name="size" value="64" />
                64×64
              </label>
              <label class="size-option">
                <input type="checkbox" name="size" value="128" />
                128×128
              </label>
              <label class="size-option">
                <input type="checkbox" name="size" value="256" />
                256×256
              </label>
            </div>
            <div class="custom-size">
              <span>自定义:</span>
              <input
                type="number"
                id="customWidth"
                min="1"
                max="512"
                placeholder="宽"
              />
              <span>×</span>
              <input
                type="number"
                id="customHeight"
                min="1"
                max="512"
                placeholder="高"
              />
              <button class="btn btn-secondary" id="addCustomSize">添加</button>
            </div>
          </div>

          <div class="option-group">
            <h4>其他选项</h4>
            <label>
              <input type="checkbox" id="keepAspect" checked />
              保持原始宽高比
            </label>
          </div>
        </div>

        <button class="btn btn-primary" id="convertBtn">
          <i class="fas fa-magic"></i>
          转换为ICO
        </button>

        <div class="preview-container" id="previewContainer">
          <div class="preview-header">
            <h3>预览</h3>
            <button class="btn btn-secondary" id="clearBtn">
              <i class="fas fa-trash-alt"></i>
              清除
            </button>
          </div>
          <div class="preview-images" id="previewImages"></div>
        </div>

        <button class="btn btn-primary download-btn" id="downloadBtn">
          <i class="fas fa-download"></i>
          下载ICO文件
        </button>
      </div>

      <div class="features">
        <div class="feature">
          <i class="fas fa-bolt"></i>
          <h3>快速转换</h3>
          <p>几秒钟内将图像转换为高质量的ICO图标</p>
        </div>
        <div class="feature">
          <i class="fas fa-lock"></i>
          <h3>安全可靠</h3>
          <p>所有处理在浏览器中完成，不上传您的文件</p>
        </div>
        <div class="feature">
          <i class="fas fa-palette"></i>
          <h3>多种尺寸</h3>
          <p>支持从16×16到256×256多种尺寸</p>
        </div>
      </div>
    </div>

    <footer>
      <p>© 2025 图像转ICO工具 - 免费在线转换服务</p>
    </footer>

    <script>
      document.addEventListener('DOMContentLoaded', function () {
        const uploadArea = document.getElementById('uploadArea')
        const fileInput = document.getElementById('fileInput')
        const convertBtn = document.getElementById('convertBtn')
        const previewContainer = document.getElementById('previewContainer')
        const previewImages = document.getElementById('previewImages')
        const downloadBtn = document.getElementById('downloadBtn')
        const clearBtn = document.getElementById('clearBtn')
        const addCustomSizeBtn = document.getElementById('addCustomSize')
        const keepAspectCheckbox = document.getElementById('keepAspect')

        let selectedFile = null
        let canvas = document.createElement('canvas')
        let ctx = canvas.getContext('2d')

        // 拖放功能
        uploadArea.addEventListener('dragover', (e) => {
          e.preventDefault()
          uploadArea.style.backgroundColor = 'rgba(72, 149, 239, 0.2)'
        })

        uploadArea.addEventListener('dragleave', () => {
          uploadArea.style.backgroundColor = 'rgba(72, 149, 239, 0.05)'
        })

        uploadArea.addEventListener('drop', (e) => {
          e.preventDefault()
          uploadArea.style.backgroundColor = 'rgba(72, 149, 239, 0.05)'

          if (e.dataTransfer.files.length) {
            handleFile(e.dataTransfer.files[0])
          }
        })

        // 点击上传
        uploadArea.addEventListener('click', () => {
          fileInput.click()
        })

        fileInput.addEventListener('change', (e) => {
          if (fileInput.files.length) {
            handleFile(fileInput.files[0])
          }
        })

        // 处理文件
        function handleFile(file) {
          const validTypes = [
            'image/png',
            'image/jpeg',
            'image/jpg',
            'image/gif',
            'image/svg+xml',
          ]

          if (!validTypes.includes(file.type)) {
            alert('请选择有效的图像文件 (PNG, JPG, JPEG, GIF, SVG)')
            return
          }

          selectedFile = file
          uploadArea.querySelector('h3').textContent = file.name
          uploadArea.querySelector('p').textContent =
            `${(file.size / 1024).toFixed(2)} KB`

          // 显示预览
          const reader = new FileReader()
          reader.onload = function (e) {
            const imgPreview = document.createElement('img')
            imgPreview.src = e.target.result
            imgPreview.style.maxWidth = '100%'
            imgPreview.style.maxHeight = '200px'

            // 清除之前的预览
            while (uploadArea.children.length > 3) {
              uploadArea.removeChild(uploadArea.lastChild)
            }

            uploadArea.appendChild(imgPreview)
          }
          reader.readAsDataURL(file)
        }

        // 添加自定义尺寸
        addCustomSizeBtn.addEventListener('click', () => {
          const width = parseInt(document.getElementById('customWidth').value)
          const height = parseInt(document.getElementById('customHeight').value)

          if (
            isNaN(width) ||
            isNaN(height) ||
            width < 1 ||
            height < 1 ||
            width > 512 ||
            height > 512
          ) {
            alert('请输入有效的尺寸 (1-512)')
            return
          }

          const sizeOptions = document.querySelectorAll('input[name="size"]')
          let exists = false

          sizeOptions.forEach((option) => {
            if (option.value === `${width}x${height}`) {
              exists = true
              option.checked = true
            }
          })

          if (!exists) {
            const newOption = document.createElement('label')
            newOption.className = 'size-option'
            newOption.innerHTML = `
                        <input type="checkbox" name="size" value="${width}x${height}" checked> ${width}×${height}
                    `
            document.querySelector('.size-options').appendChild(newOption)
          }

          document.getElementById('customWidth').value = ''
          document.getElementById('customHeight').value = ''
        })

        // 转换按钮
        convertBtn.addEventListener('click', async () => {
          if (!selectedFile) {
            alert('请先选择图像文件')
            return
          }

          const sizes = []
          document
            .querySelectorAll('input[name="size"]:checked')
            .forEach((option) => {
              if (option.value.includes('x')) {
                const [width, height] = option.value.split('x')
                sizes.push({ width: parseInt(width), height: parseInt(height) })
              } else {
                const size = parseInt(option.value)
                sizes.push({ width: size, height: size })
              }
            })

          if (sizes.length === 0) {
            alert('请至少选择一个尺寸')
            return
          }

          try {
            // 显示加载状态
            convertBtn.innerHTML =
              '<i class="fas fa-spinner fa-spin"></i> 转换中...'
            convertBtn.disabled = true

            // 创建图像对象
            const img = new Image()
            const imgUrl = URL.createObjectURL(selectedFile)

            img.onload = function () {
              // 清空预览
              previewImages.innerHTML = ''

              // 创建预览项
              sizes.forEach((size) => {
                const previewItem = document.createElement('div')
                previewItem.className = 'preview-item'

                const previewTitle = document.createElement('div')
                previewTitle.textContent = `${size.width}×${size.height}`

                const previewImg = document.createElement('img')

                // 计算新尺寸，保持宽高比
                let newWidth = size.width
                let newHeight = size.height

                if (keepAspectCheckbox.checked) {
                  const ratio = img.width / img.height
                  if (size.width / size.height > ratio) {
                    newWidth = size.height * ratio
                  } else {
                    newHeight = size.width / ratio
                  }
                }

                // 绘制到canvas
                canvas.width = size.width
                canvas.height = size.height
                ctx.clearRect(0, 0, canvas.width, canvas.height)

                // 居中绘制图像
                const x = (size.width - newWidth) / 2
                const y = (size.height - newHeight) / 2
                ctx.drawImage(img, x, y, newWidth, newHeight)

                // 添加到预览
                previewImg.src = canvas.toDataURL('image/png')
                previewItem.appendChild(previewImg)
                previewItem.appendChild(previewTitle)
                previewImages.appendChild(previewItem)
              })

              // 显示预览和下载按钮
              previewContainer.style.display = 'block'
              downloadBtn.style.display = 'inline-flex'

              // 恢复按钮状态
              convertBtn.innerHTML = '<i class="fas fa-magic"></i> 转换为ICO'
              convertBtn.disabled = false

              // 释放对象URL
              URL.revokeObjectURL(imgUrl)
            }

            img.onerror = function () {
              alert('图像加载失败，请尝试其他文件')
              convertBtn.innerHTML = '<i class="fas fa-magic"></i> 转换为ICO'
              convertBtn.disabled = false
              URL.revokeObjectURL(imgUrl)
            }

            img.src = imgUrl
          } catch (error) {
            console.error('转换出错:', error)
            alert('转换过程中出错: ' + error.message)
            convertBtn.innerHTML = '<i class="fas fa-magic"></i> 转换为ICO'
            convertBtn.disabled = false
          }
        })

        // 下载按钮
        downloadBtn.addEventListener('click', async () => {
          if (!selectedFile) return

          try {
            downloadBtn.innerHTML =
              '<i class="fas fa-spinner fa-spin"></i> 生成中...'
            downloadBtn.disabled = true

            // 获取所有选中的尺寸
            const sizes = []
            document
              .querySelectorAll('input[name="size"]:checked')
              .forEach((option) => {
                if (option.value.includes('x')) {
                  const [width, height] = option.value.split('x')
                  sizes.push({
                    width: parseInt(width),
                    height: parseInt(height),
                  })
                } else {
                  const size = parseInt(option.value)
                  sizes.push({ width: size, height: size })
                }
              })

            // 创建图像对象
            const img = new Image()
            const imgUrl = URL.createObjectURL(selectedFile)

            img.onload = function () {
              // 创建一个临时的canvas数组来存储所有尺寸
              const canvases = []

              sizes.forEach((size) => {
                const tempCanvas = document.createElement('canvas')
                const tempCtx = tempCanvas.getContext('2d')

                let newWidth = size.width
                let newHeight = size.height

                if (keepAspectCheckbox.checked) {
                  const ratio = img.width / img.height
                  if (size.width / size.height > ratio) {
                    newWidth = size.height * ratio
                  } else {
                    newHeight = size.width / ratio
                  }
                }

                tempCanvas.width = size.width
                tempCanvas.height = size.height
                const x = (size.width - newWidth) / 2
                const y = (size.height - newHeight) / 2
                tempCtx.drawImage(img, x, y, newWidth, newHeight)

                canvases.push(tempCanvas)
              })

              // 这里应该调用生成ICO的函数
              // 由于浏览器限制，实际生成ICO需要更复杂的处理
              // 这里简化为下载第一个尺寸的PNG作为示例
              const link = document.createElement('a')
              link.download =
                selectedFile.name.replace(/\.[^/.]+$/, '') + '.ico'
              link.href = canvases[0].toDataURL('image/x-icon')
              link.click()

              // 恢复按钮状态
              downloadBtn.innerHTML =
                '<i class="fas fa-download"></i> 下载ICO文件'
              downloadBtn.disabled = false

              // 释放对象URL
              URL.revokeObjectURL(imgUrl)
            }

            img.src = imgUrl
          } catch (error) {
            console.error('下载出错:', error)
            alert('生成下载文件时出错: ' + error.message)
            downloadBtn.innerHTML =
              '<i class="fas fa-download"></i> 下载ICO文件'
            downloadBtn.disabled = false
          }
        })

        // 清除按钮
        clearBtn.addEventListener('click', () => {
          selectedFile = null
          fileInput.value = ''
          previewContainer.style.display = 'none'
          downloadBtn.style.display = 'none'
          previewImages.innerHTML = ''

          // 重置上传区域
          uploadArea.querySelector('h3').textContent = '拖放图像文件到此处'
          uploadArea.querySelector('p').textContent =
            '或点击选择文件 (支持PNG, JPG, JPEG, GIF, SVG)'

          // 移除预览图像
          while (uploadArea.children.length > 3) {
            uploadArea.removeChild(uploadArea.lastChild)
          }
        })
      })
    </script>
  </body>
</html>
